﻿using System;
using System.Collections.Generic;
using System.Linq;
using CID.Domain.Development;
using CID.Domain.Operations;
using CID.Execution.Support.Scripting;
using CID.Execution.Support.Information;

namespace CID.Execution.Controller.Support
{
    class MasterActivationScript
    {
        public MasterActivationScript(Guid deploymentUniqueIdentifier, IRelease release, IEnumerable<IComponent> components, IEnvironment targetEnvironment)
        {
            DeploymentUniqueIdentifier = deploymentUniqueIdentifier;
            Release = release;
            TargetEnvironment = targetEnvironment;
            Steps = components.Select(x => new ActivationScriptStep(x, targetEnvironment)).ToArray();
        }

        public IRelease Release { get; private set; }
        public IEnvironment TargetEnvironment{ get; private set; }
        public Guid DeploymentUniqueIdentifier { get; private set; }
        public IEnumerable<ActivationScriptStep> Steps { get; private set; }

        public LocationActivationScript CreateLocationSpecific(ILocation location, IEnumerable<IComponent> includedComponents)
        {
            var includedComponentIds = includedComponents.Select(x => x.Id).ToArray();

            var result = new LocationActivationScript(DeploymentUniqueIdentifier, Release, location, 
                Steps.Where(x => includedComponentIds.Contains(x.Component.Id)).Select(x => x.Clone()).ToArray());

            foreach (var step in result.Steps)
            {
                var component = includedComponents.First(x => x.Id == step.Component.Id);
                var servers = location.Servers.Where(x => x.Enabled && (x.Assignments.Count(y => (y.ServerRole.Id == component.RequiredServerRole.Id) && (y.Environment.Id == TargetEnvironment.Id)) > 0));
                step.TargetServers = servers.Select(x => new ServerInfo(x)).ToArray();
            }

            return result;
        }
    }
}
